import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const loginUserKey = 'login-user-key';

/*
 * 设置cookie
 * setCookie('username','111',10);
 */
function setCookie(name, value, day) {
    let date = new Date();
    date.setDate(date.getDate() + day);
    document.cookie = name + "=" + value + ";expires=" + date;
}

/*
 * 获取cookie
 * let username = getCookie('username');
 */
function getCookie(name) {
    let reg = RegExp(name + "=([^;]+)");
    let arr = document.cookie.match(reg);
    if (arr) {
        return arr[1];
    } else {
        return "";
    }
}

function setSession(name, value) {
    value = (typeof value) === 'string' ? value : JSON.stringify(value);
    window.sessionStorage.setItem(name, value);
}

function getSession(name) {
    let value = window.sessionStorage.getItem(name);
    return JSON.parse(value);
}


export default new Vuex.Store({
    state: {
        userInfo: getSession(loginUserKey),  //登录用户
        socket: null,
        friend: null,
    },
    mutations: {
        setLogin(state, v) {  //设置登录用户
            state.userInfo = v;
            if (v) {
                setSession(loginUserKey, v);
            }
        },
        exitLogin() {
            setSession(loginUserKey, null);
        },
        setSocket(state, v) {
            state.socket = v;
        },
        addFriend(state, v) {
            state.friend = v;
        }
    },
    getters: {
        getLoginUser(state) {
            return state.userInfo;
        },
        getToken(state) {
            return state.userInfo ? state.userInfo.token : '';
        },
        getSocket(state) {
            return state.socket;
        }
    },
    actions: {},
    modules: {}
});
